

import gl.java.umsp.UmspHeader;
import gl.java.umsp.bean.Room;
import gl.java.umsp.bean.User;
import gl.java.umsp.event.EventServerConfig;
import gl.java.umsp.room.IRoomService;
import gl.java.umsp.room.RoomService;
import gl.java.umsp.room.RoomServiceConfig;
import gl.java.umsp.websocket.HttpRequestHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RoomServiceApplication implements IRoomService {
    public RoomService rs;
    private static RoomServiceApplication instance = null;

    public RoomServiceApplication(RoomService rs) {
        log.info("RoomServiceApplication");
        this.rs = rs;
        HttpRequestHandler.addRoute("/player", new http.RoutePlayer());
        HttpRequestHandler.addRoute("/reboot", new RebootPlayer());
        log.info("http://"+GameConfig.RoomServerIP+":8898/reboot?IP="+GameConfig.RoomServerIP+"&gameID=0");
        instance = this;
    }

    public static RoomServiceApplication getInstance() {
        return instance;
    }

    java.util.Map<String, RoomGame> roomMap = new ConcurrentHashMap();

    @Override
    public boolean onUserEnter(Room room, User user) {
        log.info("[UserEnter] " + user);
        RoomGame game = roomMap.get(room.roomID);
        if (game == null) {
            game = new RoomGame(rs, room);
            roomMap.put(room.roomID, game);
        }
        game.onUserEnter(room, user);
        return false;
    }

    @Override
    public boolean onUserExit(Room oldRoom, User user) {
        log.info("[UserExit] " + user);
        RoomGame game = roomMap.get(oldRoom.roomID);
        if (game != null) game.onUserExit(oldRoom, user);
        return false;
    }

    @Override
    public boolean onUserSendMsg(UmspHeader umspHeader, Room room) {
        RoomGame game = roomMap.get(room.roomID);
        if (game != null) return game.onUserSendMsg(umspHeader, room);
        return false;
    }

    static {
        EventServerConfig.ServerUrl = GameConfig.EventServerIP;
    }

    @Override
    public void start(Config config) {
        reg(GameConfig.RoomServerIP, 0);
    }

    public RoomServiceConfig reg(String IP, int gameID) {
        RoomServiceConfig defaultConfig = RoomServiceConfig.getDefaultConfig();
        defaultConfig.IP = IP;
        defaultConfig.gameID = gameID;
        rs.regRoomServer(defaultConfig);
        return defaultConfig;
    }

    @Override
    public void stop() {

    }


}
